<template>
  <view class="container" :style="{ paddingBottom: pageDisabled ? '0rpx' : '100rpx' }">
    <!-- 顶部选项卡 -->
    <view class="tabs-fixed">
      <up-tabs :list="tabs" :current="currentTab" @change="changeTab" lineColor="#2979ff"
               itemStyle="background:#fff;height: 80rpx;width: 100%"/>
    </view>

    <view class="form-container" style="margin-top: 90rpx">
      <up-form :model="form" :rules="rules" ref="formRef" labelPosition="left" labelWidth="160rpx">
        <!-- 基础信息 -->
        <view v-if="currentTab === 0">
          <!-- 资产概况 -->
          <view class="form-section">
            <view class="section-title">
              资产概况
              <up-tag v-if="pageDisabled && form?.asset_state_name" :text="form.asset_state_name"
                      size="mini"/>
            </view>
            <up-form-item label="资产分类" prop="asset_category" class="border-bottom" :required="true"
                          @click="handleCategory" :key="itemKeys.asset_category">
              <view @click.self="handleCategory">
                <up-input v-model="category.categoryLabel" placeholder="请选择资产分类" border="none"
                          :readonly="pageDisabled"></up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item :required="true" label="资产名称" prop="asset_name" class="border-bottom">
              <up-input v-model="form.asset_name" placeholder="请输入资产名称" border="none"
                        :readonly="pageDisabled"></up-input>
            </up-form-item>

            <up-form-item :required="true" label="资产编码" prop="asset_code" class="border-bottom">
              <up-input v-model="form.asset_code" placeholder="系统自动生成" readonly border="none"
                        placeholder-class="codePlaceholder"></up-input>
            </up-form-item>

            <up-form-item label="资产品牌" prop="brand" class="border-bottom">
              <up-input v-model="form.brand" border="none" placeholder="请填写品牌"
                        :readonly="pageDisabled"></up-input>
            </up-form-item>

            <up-form-item label="规格型号" prop="spec_model" class="border-bottom">
              <up-input v-model="form.spec_model" border="none" placeholder="规格型号"
                        :readonly="pageDisabled"></up-input>
            </up-form-item>

            <up-form-item label="标签类型" prop="tag_type" class="border-bottom">
              <up-radio-group v-model="form.tag_type" @change="groupChange" placement="row">
                <up-radio :customStyle="{ marginBottom: '8px' }" v-for="item in tagType.actions"
                          :key="item.id" :label="item.text" :name="item.value" :disabled="pageDisabled">
                </up-radio>
              </up-radio-group>
            </up-form-item>

            <up-form-item label="标签编码" prop="label_number" class="border-bottom"
                          v-if="form.tag_type === 'NORMAL_TAG'">
              <up-input v-model="form.label_number" border="none" placeholder="请扫码标签编码"
                        :readonly="pageDisabled">
              </up-input>
<!--              <template #right v-if="!pageDisabled">-->
<!--                <up-icon name="scan" @click="scanCode"></up-icon>-->
<!--              </template>-->
            </up-form-item>
            <up-form-item label="标签编码" prop="label_number" class="border-bottom" @click="handleLabelNumber"
                          v-else>
              <up-input @click.self="handleLabelNumber" v-model="labelNumber.name" border="none"
                        placeholder="请选择标签编码" :readonly="pageDisabled">
              </up-input>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="计量单位" prop="unit" class="border-bottom">
              <up-input v-model="form.unit" border="none" placeholder="计量单位"
                        :readonly="pageDisabled"></up-input>
            </up-form-item>

            <up-form-item :required="true" label="管理员" prop="asset_admin" class="border-bottom"
                          @click="handleUserAdmin('0')" :key="itemKeys.asset_admin">
              <view @click.self="handleUserAdmin('0')">
                <up-input v-model="user.admin" placeholder="请选择管理员" border="none"
                          :readonly="pageDisabled"></up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="采购价格" prop="purchase_price" class="border-bottom">
              <up-input v-model="form.purchase_price" placeholder="请输入采购价格" type="number" border="none"
                        :readonly="pageDisabled">
              </up-input>
            </up-form-item>
            <!--
            <up-form-item
              label="采购日期"
              prop="purchase_date"
              class="border-bottom"
              @click="handleDatePicker('0')"
            >
              <view @click.self="handleDatePicker('0')">
                <up-input
                  v-model="form.purchase_date"
                  placeholder="请选择日期"
                  border="none"
                  :readonly="pageDisabled"
                >
                </up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item> -->

            <up-form-item label="采购日期" prop="purchase_date" class="border-bottom">
              <uni-datetime-picker type="datetime" placeholder="请选择日期" clear-icon
                                   v-model="form.purchase_date" :class="{ 'date-color': !form.purchase_date }"
                                   :border="false" :disabled="pageDisabled" class="datetime-color"/>
            </up-form-item>
          </view>
          <!-- 使用信息 -->
          <view class="form-section">
            <view class="section-title">使用信息</view>
            <up-form-item label="使用人" prop="user" class="border-bottom" @click="handleUserAdmin('1')">
              <view @click.self="handleUserAdmin('1')">
                <up-input v-model="user.user" placeholder="请选择使用人" border="none"
                          :readonly="pageDisabled">
                </up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="使用部门" prop="department" class="border-bottom" @click="handleDepartment">
              <view @click.self="handleDepartment">
                <up-input v-model="department.name" placeholder="请选择使用部门" border="none"
                          :readonly="pageDisabled">
                </up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="存放位置" prop="location" class="border-bottom" @click="handleLocation">
              <view @click.self="handleLocation">
                <up-input v-model="location.name" border="none" placeholder="请选择存放位置"
                          :readonly="pageDisabled">
                </up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="资产来源" prop="asset_source" class="border-bottom" @click="handleSource">
              <view @click.self="handleSource">
                <up-input v-model="source.name" border="none" placeholder="请选择资产来源"
                          :readonly="pageDisabled">
                </up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="SN码" prop="sn_code" class="border-bottom">
              <up-input v-model="form.sn_code" border="none" placeholder="SN码"
                        :readonly="pageDisabled"></up-input>
            </up-form-item>
          </view>
          <!-- 折旧信息 -->
          <view class="form-section">
            <view class="section-title">折旧信息</view>
            <up-form-item label="有效期" prop="accounting_date" class="border-bottom">
              <uni-datetime-picker type="datetime" placeholder="请选择日期" clear-icon
                                   v-model="form.accounting_date" :border="false" :disabled="pageDisabled"
                                   :class="{ 'date-color': !form.accounting_date }" class="datetime-color"/>
            </up-form-item>

            <up-form-item label="资产净残值" prop="asset_salvage_value" class="border-bottom">
              <up-input v-model="form.asset_salvage_value" placeholder="请填写资产净残值金额" type="number"
                        border="none" :readonly="pageDisabled">
              </up-input>
            </up-form-item>

            <up-form-item label="月折旧率" prop="monthly_depreciation_rate" class="border-bottom">
              <up-input v-model="form.monthly_depreciation_rate" placeholder="月折旧率=(采购价-净残值)/使用年限/采购价"
                        border="none" :readonly="pageDisabled">
              </up-input>
            </up-form-item>

            <up-form-item label="资产现值" prop="current_value" class="border-bottom">
              <up-input v-model="form.current_value" placeholder="现值=采购价-已折旧值" border="none"
                        :readonly="pageDisabled">
              </up-input>
            </up-form-item>

            <up-form-item label="资产图片（限制大小为2MB）" prop="image" labelPosition="top" labelWidth="500rpx">
              <up-upload style="margin-top: 20rpx" :fileList="fileList" @afterRead="afterRead"
                         @delete="deletePic" :disabled="pageDisabled" :deletable="!pageDisabled" name="image"
                         :maxCount="1" :maxSize="2 * 1024 * 1024" width="250" height="150"
                         previewFullImage></up-upload>
            </up-form-item>

            <view class="section-title">备注</view>
            <up-form-item prop="remark">
              <up-textarea v-model="form.remark" :disabled="pageDisabled"
                           placeholder="要留下点什么吗"></up-textarea>
            </up-form-item>
          </view>
        </view>

        <!-- 维保信息 -->
        <view v-if="currentTab === 1">
          <view class="form-section">
            <view class="section-title">供应商信息</view>
            <up-form-item label="供应商" prop="supplier" class="border-bottom" @click="handleSupplier">
              <view @click.self="handleSupplier">
                <up-input v-model="supplier.supplierLabel" placeholder="请选择供应商" border="none"
                          :readonly="pageDisabled"></up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>

            <up-form-item label="联系人" prop="supplier_contact" class="border-bottom">
              <up-input v-model="form.supplier_contact" border="none" :readonly="pageDisabled"></up-input>
            </up-form-item>
            <up-form-item label="联系方式" prop="supplier_phone" class="border-bottom">
              <up-input v-model="form.supplier_phone" border="none" :readonly="pageDisabled"></up-input>
            </up-form-item>

            <up-form-item label="负责人" prop="manager" class="border-bottom" @click="handleUserAdmin('2')">
              <view @click.self="handleUserAdmin('2')">
                <up-input v-model="user.manager" placeholder="请选择负责人" border="none"
                          :readonly="pageDisabled"></up-input>
              </view>
              <template #right>
                <up-icon name="arrow-right"></up-icon>
              </template>
            </up-form-item>
          </view>
        </view>

        <!-- 附件信息 -->
        <view v-if="currentTab === 2">
          <view class="form-section" style="padding: 20rpx">
            <!-- 上传规则提示文本 -->
            <view v-if="!pageDisabled" style="margin-bottom: 10rpx; font-size: 24rpx; color: #888">
              支持上传格式：
              <text style="color: red">png, jpg, jpeg, pdf, txt, doc, docx, xls, xlsx</text>
              ， 最大文件：
              <text style="color: red">{{ maxSize / 1024 / 1024 }}MB</text>
              ，
              最多上传：
              <text style="color: red">{{ maxCount }} 个文件</text>
            </view>

            <up-button type="primary" v-if="!pageDisabled" @click="selectFile">点击上传文件</up-button>
            <!-- 已选文件展示 -->
            <view v-if="attachmentsUpload[0].files.length" style="margin-top: 10rpx">
              已上传文件：
              <view style="display: flex" v-for="items in attachmentsUpload[0].files" :key="items.id">
                <text style="color: red" @click="handleDownFile(items)">{{
                    items.name
                  }}
                </text>
                <up-icon v-if="!pageDisabled" @click="handleClose(items)" name="close" color="#ccc"/>
              </view>
            </view>
          </view>
        </view>
      </up-form>
    </view>

    <!-- 提交按钮 -->
    <view class="footer" v-if="!pageDisabled">
      <up-button type="primary" text="提交" @click="submitForm"></up-button>
    </view>

    <!-- 日期选择器 -->
    <up-datetime-picker :show="datePicker.show" mode="datetime" v-model="dateTime" closeOnClickOverlay
                        @confirm="confirmDate" @cancel="birthdayClose" @close="birthdayClose"
                        :formatter="formatter"></up-datetime-picker>
    <!-- 选资产 -->
    <up-action-sheet :show="category.show" :actions="category.actions" title="请选择" @close="category.show = false"
                     @select="categorySelect">
    </up-action-sheet>
    <!-- 选人 -->
    <up-action-sheet :show="user.show" :actions="user.actions" title="请选择" @close="user.show = false"
                     @select="userSelect">
    </up-action-sheet>
    <!-- 选部门 -->
    <up-action-sheet :show="department.show" :actions="department.actions" title="请选择"
                     @close="department.show = false" @select="departmentSelect">
    </up-action-sheet>
    <!-- 选存放位置 -->
    <up-action-sheet :show="location.show" :actions="location.actions" title="请选择" @close="location.show = false"
                     @select="locationSelect">
    </up-action-sheet>

    <!-- 选资产来源 -->
    <up-action-sheet :show="source.show" :actions="source.actions" title="请选择" @close="source.show = false"
                     @select="sourceSelect">
    </up-action-sheet>

    <!-- 选供应商 -->
    <up-action-sheet :show="supplier.show" :actions="supplier.actions" title="请选择" @close="supplier.show = false"
                     @select="supplierSelect">
    </up-action-sheet>

    <!-- 选标签 -->
    <up-action-sheet :show="labelNumber.show" :actions="labelNumber.actions" title="请选择"
                     @close="labelNumber.show = false" @select="labelNumberSelect">
    </up-action-sheet>
  </view>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  onUnmounted
} from "vue";
import {
  onLoad,
  onUnload,
} from "@dcloudio/uni-app";
import {
  generateUUID,
  formatter,
  formatDateTime
} from "@/utils";
import http, {
  BASE_URL
} from "@/api/request";
import {
  t
} from "@/locale/index.js";

import fileSys from "@/utils/fileSys";

const plugin = uni.requireNativePlugin('RFIDPlugin')
var main, receiver, filter;

const formRef = ref(null);
const pageId = ref("");
const currentTab = ref(0);
const datePicker = reactive({
  type: "0",
  show: false,
});

const topOffset = ref(0);
const state = ref("");

const pageDisabled = ref(false);

const itemKeys = reactive({
  asset_category: Date.now(),
  asset_admin: Date.now() + 1,
});

const initScan = () => {
  const res = plugin.initScan()
  if (!res) {
    uni.showToast({
      title: '初始化扫描失败',
      icon: 'none'
    })
    return
  }
  main = plus.android.runtimeMainActivity();
  var IntentFilter = plus.android.importClass('android.content.IntentFilter');
  filter = new IntentFilter();
  //下面的addAction内改为自己的广播动作
  filter.addAction("android.scanservice.action.UPLOAD_BARCODE_DATA"); //按键广播
  filter.addAction("com.safeuem.doublebird.appReadyToInstall"); //超高频tag广播
  receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
    onReceive: function (context, intent) {
      plus.android.importClass(intent);
      let m_action = intent.getAction();
      if (m_action == "com.safeuem.doublebird.appReadyToInstall") { //接收到按键广播，处理按键广播事件
        console.log('com.safeuem.doublebird.appReadyToInstall')
      } else {
        let code = intent.getStringExtra("barcode");
        form.value.label_number = code
      }
    }
  });
  main.registerReceiver(receiver, filter);
}

const unInitScan = () => {
  main.unregisterReceiver(receiver);
  plugin.stopScan()
}

onMounted(() => {
  initScan()
})

onUnmounted(() => {
  unInitScan()
})

onLoad(async (query) => {
  await getDataList();
  const info = uni.getSystemInfoSync();
  const data = uni.getStorageSync("assetInfoData");
  const statusBarHeight = info.statusBarHeight || 0;
  const navBarHeight = 44; // 通常为 44 px
  topOffset.value = statusBarHeight + navBarHeight;
  if (query.name === "add") {
    uni.setNavigationBarTitle({
      title: t("assetsPages.add"),
    });
    pageDisabled.value = false;
  } else if (query.name === "edit") {
    uni.setNavigationBarTitle({
      title: t("assetsPages.edit"),
    });
    form.value = data;
    pageDisabled.value = false;
  } else if (query.name === "detail") {
    uni.setNavigationBarTitle({
      title: t("assetsPages.detail"),
    });
    form.value = data;
    pageDisabled.value = true;
  }
  state.value = query.name;
  category.categoryLabel = category.actions.find(
      (item) => item.value === data?.asset_category
  )?.name;
  user.admin = user.actions.find(
      (item) => item.value === data?.asset_admin
  )?.name;
  user.user = user.actions.find((item) => item.value === data?.user)?.name;
  user.manager = user.actions.find(
      (item) => item.value === data?.manager
  )?.name;

  department.name = department.actions.find(
      (item) => item.value === data?.department
  )?.name;
  location.name = location.actions.find(
      (item) => item.value === data?.location
  )?.name;
  source.name = source.actions.find(
      (item) => item.value === data?.asset_source
  )?.name;
  supplier.supplierLabel = supplier.actions.find(
      (item) => item.value === data?.supplier
  )?.name;
  if (form.value.tag_type === "RFID_TAG") {
    labelNumber.name = data?.label_number;
  }
  if (form.value.id) {
    await getFiles();
  }
  // 获取页面信息
  await getPageInfo();
});


const getFiles = async () => {
  const postData = {
    linkId: "1",
    taskId: form.value.id,
  };
  const {
    code,
    isSuccess,
    result
  } = await http.post(
      "/api/file/GetTaskLinkedFiles",
      postData
  );
  if (code && isSuccess && result) {
    result.forEach((item) => {
      attachmentsUpload.value[0].files.push({
        id: item.id,
        name: item.fileName + "  " + item.userName + "  " + item.creationTime,
        url: `/File/Download?fileId=` + item.id,
      });
    });
  }
};

const getPageInfo = async () => {
  const data = {
    assetlist: "assetlist",
    pageCode: "assetlistadd",
  };

  const {
    code,
    isSuccess,
    result
  } = await http.post(
      "/api/page/GetPageInfoByCode",
      data
  );
  if (code && isSuccess) {
    pageId.value = result.page.parentPageId;
  }
};

onUnload(() => {
  uni.removeStorageSync("assetInfoData");
});

const tabs = ref([{
  name: "基础信息"
},
  {
    name: "维保信息"
  },
  {
    name: "附件信息"
  },
]);

const fileList = computed(() => {
  return (form.value.image || "")
      .split(",")
      .filter(Boolean)
      .map((id) => ({
        url: `${BASE_URL}/File/GetImage?fileId=${id}`,
      }));
});

const maxSize = 10 * 1024 * 1024; // 10MB
const maxCount = 10;
const allowedExts = [
  "png",
  "jpg",
  "jpeg",
  "pdf",
  "txt",
  "doc",
  "docx",
  "xls",
  "xlsx",
];

const enumList = [{
  code: "getViewTable",
  name: "getAssetClassList"
},
  {
    code: "getviewTable",
    name: "Sys_GetUserNameById"
  },
  {
    code: "getviewTable",
    name: "Sys_GetGroupNameById"
  },
  {
    code: "getviewTable",
    name: "getAssetAddressList"
  },
  {
    code: "getviewTable",
    name: "getAssetSourcePage"
  },
  {
    code: "getviewTable",
    name: "getSupplierList"
  },
  {
    code: "getBasicData",
    name: "asset>tag_type"
  },
  {
    code: "getviewTable",
    name: "getTagsByCondition"
  },
];

const form = ref({
  // 基础信息
  asset_category: "",
  asset_name: "",
  asset_code: "",
  brand: "",
  spec_model: "",
  label_number: "",
  unit: "",
  tag_type: "",
  asset_admin: "",
  purchase_price: "",
  purchase_date: "",
  user: "",
  department: "",
  location: "",
  asset_source: "",
  sn_code: "",
  accounting_date: "",
  asset_salvage_value: "",
  monthly_depreciation_rate: "",
  current_value: "",
  image: "",
  remark: "",
  // 维保信息
  supplier: "",
  supplier_contact: "",
  supplier_phone: "",
  manager: "",
  attachment: "",
});

const attachmentsUpload = ref([{
  Fileld: [],
  files: [],
  linkId: "1",
  taskId: "<%assetlistmstr.id%>",
},]);

const rules = {
  asset_category: {
    type: "string",
    required: true,
    message: "请选择资产分类",
    trigger: ["blur", "change"],
  },
  asset_name: {
    type: "string",
    required: true,
    message: "请输入资产名称",
    trigger: ["blur", "change"],
  },
  asset_code: {
    type: "string",
    required: false,
    message: "请输入资产编码",
    trigger: ["blur", "change"],
  },
  asset_admin: {
    type: "string",
    required: true,
    message: "请选择管理员",
    trigger: ["blur", "change"],
  },
};

const category = reactive({
  show: false,
  categoryLabel: "",
  actions: [],
});
const user = reactive({
  show: false,
  type: "0",
  admin: "",
  user: "",
  manager: "",
  actions: [],
});

const department = reactive({
  show: false,
  name: "",
  actions: [],
});

const location = reactive({
  show: false,
  name: "",
  actions: [],
});
const source = reactive({
  show: false,
  name: "",
  actions: [],
});

const supplier = reactive({
  show: false,
  supplierLabel: "",
  actions: [],
});

const labelNumber = reactive({
  show: false,
  name: "",
  actions: [],
});

const tagType = reactive({
  actions: [],
});

const dateTime = ref(Number(new Date()));

const handleCategory = () => {
  if (!pageDisabled.value) {
    category.show = true;
    hideKeyboard();
  }
};

const handleLabelNumber = () => {
  if (!pageDisabled.value) {
    labelNumber.show = true;
    hideKeyboard();
  }
};

const handleUserAdmin = (value) => {
  if (!pageDisabled.value) {
    user.show = true;
    user.type = value;
    hideKeyboard();
  }
};

const handleDatePicker = (value) => {
  if (!pageDisabled.value) {
    datePicker.show = true;
    datePicker.type = value;
    hideKeyboard();
  }
};

const handleDepartment = () => {
  if (!pageDisabled.value) {
    department.show = true;
    hideKeyboard();
  }
};

const handleLocation = () => {
  if (!pageDisabled.value) {
    location.show = true;
    hideKeyboard();
  }
};

const handleSource = () => {
  if (!pageDisabled.value) {
    source.show = true;
    hideKeyboard();
  }
};

const handleSupplier = () => {
  if (!pageDisabled.value) {
    supplier.show = true;
    hideKeyboard();
  }
};

// 获取资产列表
const getDataList = async () => {
  const batchRequests = enumList.map((item) => {
    const params = [{
      id: generateUUID(),
      service: "Module",
      method: item.code,
      param: item.name === "asset>tag_type" ?
          JSON.stringify({
            code: item.name,
            filters: [{
              name: "filter",
              value: "B"
            }],
          }) : item.name === "getTagsByCondition" ?
              JSON.stringify({
                code: item.name,
                filters: [{
                  name: "usage_status",
                  value: "NOT_USED"
                }],
              }) : JSON.stringify({
                code: item.name,
                filters: [{
                  name: "usage_status",
                  value: "NOT_USED"
                }],
              }),
    },];
    return http.post("/api/module/GetBatchResult", params).then((res) => ({
      ...res,
      name: item.name,
    }));
  });

  try {
    const results = await Promise.all(batchRequests);

    results.forEach(({
                       name,
                       result,
                       isSuccess,
                       code
                     }) => {
      if (!isSuccess || !code) return;
      switch (name) {
        case "getAssetClassList":
          category.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.asset_class_name,
              value: item.asset_class_code,
            };
          });
          break;
        case "Sys_GetUserNameById":
          user.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.text,
              value: item.id,
            };
          });
          break;
        case "Sys_GetGroupNameById":
          department.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.text,
              value: item.id,
            };
          });
          break;
        case "getAssetAddressList":
          location.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.asset_address_name,
              value: item.asset_address_code,
            };
          });
          break;

        case "getAssetSourcePage":
          source.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.asset_source_name,
              value: item.asset_source_code,
            };
          });
          break;
        case "getSupplierList":
          supplier.actions = result[0].response.data.viewTable.map((item) => {
            return {
              ...item,
              name: item.name,
              value: item.code,
            };
          });
          break;

        case "asset>tag_type":
          tagType.actions = result[0].response.data.data;
          form.value.tag_type = tagType.actions[0].value;
          break;

        case "getTagsByCondition":
          labelNumber.actions = result[0].response.data.viewTable.map(
              (item) => {
                return {
                  ...item,
                  name: item.label_code,
                  value: item.label_code,
                };
              }
          );
          break;
      }
    });
  } catch (error) {
    console.error("获取枚举失败:", error);
  }
};

const categorySelect = (item) => {
  form.value.asset_category = item.value;
  category.categoryLabel = item.name;

  form.value.asset_name = item.asset_class_name;
  form.value.spec_model = item.asset_class_spec;
  form.value.unit = item.asset_class_unit;
  form.value.sn_code = item.asset_class_sn;
  form.value.purchase_price = item.asset_class_price;
  form.value.asset_salvage_value = item.asset_class_salvage;
  form.value.monthly_depreciation_rate = item.asset_class_monthly_depre_rate;
  formRef.value.validateField("asset_category");
};

const labelNumberSelect = (item) => {
  form.value.label_number = item.value;
  labelNumber.name = item.name;
};

const hideKeyboard = () => {
  uni.hideKeyboard();
};

const userSelect = (e) => {
  if (user.type === "0") {
    form.value.asset_admin = e.value;
    user.admin = e.name;
    formRef.value.validateField("asset_admin");
  } else if (user.type === "1") {
    form.value.user = e.value;
    user.user = e.name;
  } else if (user.type === "2") {
    form.value.manager = e.value;
    user.manager = e.name;
  }
};

const departmentSelect = (e) => {
  form.value.department = e.value;
  department.name = e.name;
};

const locationSelect = (e) => {
  form.value.location = e.value;
  location.name = e.name;
};

const sourceSelect = (e) => {
  form.value.asset_source = e.value;
  source.name = e.name;
};

const supplierSelect = (e) => {
  form.value.supplier = e.value;
  supplier.supplierLabel = e.name;

  form.value.supplier_contact = e.contacts;
  form.value.supplier_phone = e.contact_number;
};

// 图片上传
const afterRead = async (event) => {
  uni.showLoading({
    title: "上传中...",
    mask: true,
  });
  const file = event.file;
  try {
    const res = await http.upload({
      url: "/fileApi/File/UploadFiles",
      filePath: file.url,
      name: "file",
      formData: {
        type: "image",
      },
    });

    uni.showToast({
      title: "上传成功",
      icon: "success"
    });
    const {
      result
    } = res;
    const newIds = result.map((item) => item.id);
    const current = (form.value.image || "").split(",").filter(Boolean);
    form.value.image = [...current, ...newIds].join(",");
    uni.hideLoading();
  } catch (err) {
    uni.showToast({
      title: "上传失败",
      icon: "error"
    });
    uni.hideLoading();
  }
};

const selectFile = () => {
  if (attachmentsUpload.value[0].files.length === 10) {
    uni.showLoading({
      title: "超出限制！",
      type: "error",
    });
  } else {
    fileSys().then((res) => {
      console.log(res, "res");
      const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
      attachmentsUpload.value[0].files.push({
        id: res[0].id,
        name: (res[0].fileName || "未知文件") +
            "  " +
            userInfo.name +
            "  " +
            formatDateTime(new Date()),
        url: `/File/Download?fileId=` + res[0].id,
      });
    });
  }
  setTimeout(() => {
    uni.hideLoading();
  }, 1500);
};

const handleDownFile = (items) => {
  uni.downloadFile({
    url: BASE_URL + items.url,
    success: (res) => {
      if (res.statusCode === 200) {
        plus.runtime.openFile(res.tempFilePath, {}, (e) => {
          uni.showModal({
            title: "无法打开文件",
            content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
            confirmText: "去安装",
            success: (modalRes) => {
              if (modalRes.confirm) {
                try {
                  plus.runtime.openURL(
                      'market://details?id=com.tencent.mtt',
                      () => {
                        plus.runtime.openURL(
                            'https://browser.qq.com');
                      });
                } catch (e) {
                  plus.runtime.openURL('https://browser.qq.com');
                }
              }
            },
          });
        });
      }
    },
    fail: (err) => {
      console.error("下载失败", err);
      uni.showToast({
        title: "下载失败",
        icon: "none"
      });
    },
  });
};

// 删除图片信息
const deletePic = (event) => {
  if (!event?.file?.url) return;

  const deletedUrl = event.file.url;

  const match = deletedUrl.match(/fileId=([^&]+)/);
  const fileId = match ? match[1] : null;

  if (!fileId) return;

  const currentList = (form.value.image || "").split(",").filter(Boolean);
  form.value.image = currentList.filter((id) => id !== fileId).join(",");
};

// 扫码
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      form.value.label_number = res.result;
    },
    fail: (err) => {
      console.error("扫码失败:", err);
    },
  });
};

// 日期选择
const confirmDate = (e) => {
  datePicker.show = false;
  if (datePicker.type == "0") {
    form.value.purchase_date = result(e.value, e.mode);
  } else if (datePicker.type == "1") {
    form.value.accounting_date = result(e.value, e.mode);
  }
};

const result = (time, mode) => {
  const timeFormat = uni.$u.timeFormat;
  return timeFormat(time, "yyyy-mm-dd hh:MM");
};

const birthdayClose = () => {
  datePicker.show = false;
};

// 切换标签页
const changeTab = (value) => {
  currentTab.value = value.index;
};

const getTagsByCondition = (labelCode, callback) => {

}

// 提交表单
const submitForm = async () => {
  try {
    // Validate form first
    await formRef.value.validate();

    uni.showLoading({
      title: "提交中...",
    });

    // Prepare tag update data
    let tagUpdateData = null;
    let oldTagId = null;

    // Handle RFID tag status if this is an RFID tag
    if (form.value.tag_type === 'RFID_TAG' && form.value.label_number) {
      // Check the new tag status
      const newTagInfo = await checkTagStatus(form.value.label_number);

      if (!newTagInfo) {
        uni.hideLoading();
        uni.showToast({
          title: "未找到对应的RFID标签信息",
          icon: "error"
        });
        return;
      }

      // For edit case, check if we need to release old tag
      if (state.value === "edit") {
        const oldData = uni.getStorageSync("assetInfoData");
        if (oldData?.label_number && oldData.label_number !== form.value.label_number) {
          const oldTagInfo = await checkTagStatus(oldData.label_number);
          if (oldTagInfo) {
            oldTagId = oldTagInfo.id;
          }
        }
      }

      // Prepare tag update data
      tagUpdateData = {
        id: newTagInfo.id,
        usage_status: 'USED'
      };
    }

    // Prepare the main form data
    const rawData = {
      ...form.value,
      attachment: attachmentsUpload.value?.[0]?.files?.length ?
          attachmentsUpload.value[0].files.map((item) => item.id).join(",") : "",
    };

    // Remove empty values
    const dataObjct = Object.fromEntries(
        Object.entries(rawData).filter(
            ([_, value]) => value !== "" && value !== null && value !== undefined
        )
    );

    let data;
    if (state.value === "add") {
      // 当资产已分配到使用人，则该资产新增后状态显示“已使用”，如果无分配到个人，即使用部门及使用人为空，则该资产新增后状态显示“闲置”。
      dataObjct.asset_state = (dataObjct.user && dataObjct.user != '') ? 'IN_USE' : 'IDLE';

      data = {
        pageId: pageId.value,
        methodName: "doSaveTableData",
        saveTableDataRequest: {
          data: {
            insert: {
              assetlistmstr: {
                data: dataObjct,
              },
            },
            update: tagUpdateData ? {
              tagmstr: {
                data: tagUpdateData
              }
            } : {},
            remove: {},
            updateWhere: {},
            removeWhere: {},
            otherData: {
              fileAttachments: attachmentsUpload.value,
            },
            savedInvoke: {},
            pageAuths: [],
          },
        },
      };
    } else if (state.value === "edit") {
      // 如果之前是IDLE状态，并且修改的时候加上了使用人，则变更状态为使用中
      if (dataObjct.user && dataObjct.user != '' && dataObjct.asset_state == 'IDLE') {
        dataObjct.asset_state = 'IN_USE';
      }
      // 如果之前是IN_USE状态，并且修改的时候移除了使用人，则变更状态为闲置中
      if ((!(dataObjct.user) || dataObjct.user == '') && dataObjct.asset_state == 'IN_USE') {
        dataObjct.asset_state = 'IDLE';
      }

      // Prepare the update object
      const updateObj = {
        assetlistmstr: {
          data: dataObjct,
        },
      };

      // Handle tag updates if needed
      if (tagUpdateData) {
        if (oldTagId) {
          // Both new and old tags need updates
          updateObj.tagmstr = {
            data: [
              tagUpdateData, // New tag to be marked as USED
              {
                id: oldTagId,
                usage_status: 'NOT_USED' // Old tag to be released
              }
            ]
          };
        } else {
          // Only new tag needs update
          updateObj.tagmstr = {
            data: tagUpdateData
          };
        }
      }

      data = {
        pageId: pageId.value,
        methodName: "doSaveTableData",
        saveTableDataRequest: {
          data: {
            insert: {
              assetlistmstr: {
                data: [],
              },
            },
            update: updateObj,
            remove: {},
            updateWhere: {},
            removeWhere: {},
            otherData: {
              fileAttachments: attachmentsUpload.value,
            },
            savedInvoke: {},
            pageAuths: [],
          },
        },
      };
    }

    // Submit the data
    const res = await http.post("/api/module/Invoke", data);

    if (res.code && res.isSuccess) {
      uni.hideLoading();
      uni.showToast({
        title: "提交成功",
        icon: "success",
      });

      // Reset form if this was an add operation
      if (state.value === "add") {
        formRef.value?.resetFields();
        form.value = {
          asset_category: "",
          asset_name: "",
          asset_code: "",
          brand: "",
          spec_model: "",
          label_number: "",
          unit: "",
          tag_type: "",
          asset_admin: "",
          purchase_price: "",
          purchase_date: "",
          user: "",
          department: "",
          location: "",
          asset_source: "",
          sn_code: "",
          accounting_date: "",
          asset_salvage_value: "",
          monthly_depreciation_rate: "",
          current_value: "",
          image: "",
          remark: "",
          supplier: "",
          supplier_contact: "",
          supplier_phone: "",
          manager: "",
          attachment: "",
        };
        attachmentsUpload.value = [{
          Fileld: [],
          files: [],
          linkId: "1",
          taskId: "<%assetlistmstr.id%>",
        }];
        category.categoryLabel = "";
        user.admin = "";
        user.user = "";
        user.manager = "";
        department.name = "";
        location.name = "";
        source.name = "";
        supplier.supplierLabel = "";
        labelNumber.name = "";
      }

      // Force re-render of form items
      itemKeys["asset_category"] = Date.now();
      itemKeys["asset_admin"] = Date.now() + 1;

      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.hideLoading();
      uni.showToast({
        title: res.error || "提交失败",
        icon: "error"
      });
    }
  } catch (err) {
    console.error("表单验证失败:", err);
    uni.hideLoading();
    uni.showToast({
      title: "表单验证失败",
      icon: "error"
    });
  }
};

const checkTagStatus = async (labelCode) => {
  try {
    const params = {
      allColumnFilter: true,
      code: 'getTagsByCondition',
      filters: [{
        name: 'label_code_eq',
        value: labelCode
      },],
      pageInput: {
        currentPage: 1,
        pageSize: 999
      },
      permissionKey: ""
    };

    const res = await http.post('/api/module/GetViewTable', params);
    if (res.code && res.isSuccess) {
      return res.result.viewTable[0]; // Return the first matching tag
    }
    return null;
  } catch (err) {
    console.error(err);
    return null;
  }
}

const groupChange = (items) => {
  form.value.label_number = "";
  labelNumber.name = "";
};

const handleClose = (items) => {
  attachmentsUpload.value[0].files = attachmentsUpload.value[0].files.filter(
      (item) => item.id !== items.id
  );
};
</script>

<style lang="scss" scoped>
.container {
  padding-bottom: 100rpx;
  background-color: #f7f7f7;
}

.form-container {
  padding: 20rpx 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  padding: 24rpx 0;
  color: #333;
  border-bottom: 1rpx solid #f5f5f5;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

:deep(.up-form-item__body) {
  padding: 20rpx 0;
}

:deep(.up-form-item__body__left__content) {
  font-size: 28rpx;
  color: #666;
}

:deep(.up-form-item__body__right__content) {
  flex: 1;
  text-align: right;
}

:deep(.up-input__content__field-wrapper__field) {
  text-align: right;
}

.codePlaceholder {
  color: #000 !important;
}

.border-bottom {
  border-bottom: 1px solid #f5f5f5;
}

.tabs-fixed {
  position: fixed;
  top: var(--window-top, 0px);
  left: 0;
  width: 100%;
  z-index: 999;
  background-color: #fff;
}

:deep(.datetime-color .uni-date__x-input) {
  color: #000 !important;
  opacity: 1 !important;
}

:deep(.date-color .uni-date__x-input) {
  color: #c2c7ce !important;
  opacity: 1 !important;
}

:deep(.uni-date-editor--x__disabled) {
  opacity: 1 !important;
}
</style>